<!--
 * @Description: 任务--新增、编辑弹窗
 * @Author: Caroline
 * @Date: 2024-01-16 20:06:43
 * @LastEditTime: 2024-03-13 10:36:47
 * @LastEditors: Caroline
 * @FilePath: \Evaluation-web\src\views\task\add-or-update.vue
-->
<template>
  <el-dialog v-model="visible" width="700px" :title="isEdit ? $t('update') : $t('add')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" label-position="top" :inline="true" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <!-- 任务名称 -->
      <el-form-item prop="name" :label="$t('task.name')">
        <el-input v-model="dataForm.name" :placeholder="$t('task.name')"></el-input>
      </el-form-item>

      <!-- 关联项目 -->
      <el-form-item prop="projectName" :label="$t('task.projectName')">
        <el-select v-model="dataForm.project" clearable filterable value-key="id" :placeholder="$t('task.projectName')">
          <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item"></el-option>
        </el-select>
      </el-form-item>

      <!-- 人员薪资（薪资-单位） -->
      <el-form-item prop="salary" class="full" :label="$t('task.salary')" label-position="left">
        <el-row style="flex: 1">
          <el-col :span="18">
            <el-input type="number" :autosize="{ minRows: 2, maxRows: 4 }" v-model="dataForm.salary" :placeholder="$t('task.salary')"></el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="dataForm.salaryType" :placeholder="$t('task.salaryType')">
              <el-option v-for="item in salaryTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 测评时间 -->
      <el-form-item prop="evaluateTimeList" class="full" :label="$t('task.evaluateTime')">
        <el-date-picker ref="datesRef" @change="onDateChange" type="dates" v-model="dataForm.evaluateTimeList" :editable="false" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :placeholder="$t('task.evaluateTime')"></el-date-picker>
      </el-form-item>

      <!-- 测评人员 -->
      <el-form-item prop="userIds" class="full" :label="$t('task.userIds')" label-position="left">
        <el-select v-model="dataForm.userIdList" clearable filterable :multiple="true" :placeholder="$t('task.userIds')">
          <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item prop="notes" class="full" :label="$t('task.notes')">
        <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" v-model="dataForm.notes" :placeholder="$t('task.notes')"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import baseService from "@/service/baseService";
import { getToken } from "@/utils/cache";
import { formatDate } from "@/utils/date";
import { SALARY_TYPE, salaryTypeList } from "./type";

const { t } = useI18n();

const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();

type FormDataType = {
  id: string;
  name: string;
  project: { id: string; name: string };
  salary: number | string;
  salaryType: SALARY_TYPE | string;
  evaluateTimeList: string[];
  userIdList: string[];
  notes: string;
};
const dataForm = ref<FormDataType>({
  id: "",
  name: "",
  project: { id: "", name: "" },
  salary: "",
  salaryType: "",
  evaluateTimeList: [],
  userIdList: [],
  notes: ""
});

const isEdit = computed(() => {
  return !!dataForm.value.id;
});

// 测评人员集合
const userList = ref<{ id: string; name: string }[]>([]);
const getEvaluatorList = () => {
  baseService
    .get("/sys/user/free/list", {
      freeTimes: dataForm.value.evaluateTimeList?.join(",")
    })
    .then((res) => {
      userList.value = (res.data || []).map(({ id, realName }: { id: string; realName: string }) => {
        return { id, name: realName };
      });
    });
};

// 项目集合
const projectList = ref<{ id: string; name: string }[]>([]);
const getProjectList = () => {
  baseService.get("/assess/assessproject/page", { limit: 1000 }).then((res) => {
    projectList.value = res.data?.list || [];
  });
};
getProjectList();

// 测评时间发生变化时
const onDateChange = () => {
  getEvaluatorList();
};

// 初始化
const init = (row: any) => {
  visible.value = true;

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  const { id = "", name = "", projectId = "", projectName = "", salary = "", salaryType = "", assessTime = "", userIds, notes = "" } = row;
  dataForm.value = {
    id,
    name,
    project: { id: projectId, name: projectName },
    salary,
    salaryType,
    evaluateTimeList: assessTime?.split(",") || [],
    userIdList: userIds?.split(",") || [],
    notes
  };
  getEvaluatorList();
};

// 表单rules
const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }]
});

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }

    const { id, name, project, salary, salaryType, evaluateTimeList, userIdList, notes } = dataForm.value;
    const params = {
      id,
      name,
      projectId: project.id,
      projectName: project.name,
      salary: +salary,
      salaryType,
      assessTime: evaluateTimeList.join(","),
      userIds: userIdList?.join(","),
      notes
    };
    (dataForm.value.id ? baseService.put : baseService.post)("/assess/assesstask", params).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
<style lang="less" scoped>
.title {
  line-height: var(--el-dialog-font-line-height);
  font-size: var(--el-dialog-title-font-size);
  color: var(--el-text-color-primary);
}
:deep(.el-form-item) {
  width: calc(50% - 16px);
  &.full {
    width: 100%;
  }
}
</style>
